import React from "react";
import {
	observable,
	action,
} from "mobx";

class SearchData {
	@observable searchString = {
		houseAddress: "",
		isLoading: false,
		message: "",
		result: [],
	};
	//获取ＡＰＩ的接口；
	@action urlForQueryAndPage(key, value, pageNumber) {
		var data = {
			country: 'uk',
			pretty: '1',
			encoding: 'json',
			listing_type: 'buy',
			action: 'search_listings',
			page: pageNumber
		};
		data[key] = value;

		var querystring = Object.keys(data)
			.map(key => key + '=' + encodeURIComponent(data[key]))
			.join('&');

		return 'https://api.nestoria.co.uk/api?' + querystring;
	};
	//发起ＡＰＩ请求；
	@action async getFetch() {
			const url = this.urlForQueryAndPage('place_name', this.searchString.houseAddress, 1);
			console.log(url);
			await fetch(`${url}`)
				.then(response => {
					return response.json()
				})
				.then(jsonData => {
					this.searchString.isLoading = false;
					this.searchString.message = "";
					if (jsonData.response.application_response_code.substr(0, 1) === '1') {
						console.log('Properties found: ' + jsonData.response.listings.length);
						this.searchString.result = jsonData.response.listings;
					} else {
						this.searchString.result.length = 0;
						this.searchString.message = "Location not recognized; please try again.";
					}
				})
				.catch(error => {
					this.searchString.isLoading = false;
					this.searchString.message = "数据请求失败，请稍后重试";
				})
		}
		//获取本地的房产信息；
	@action async getLocationFetch(url) {
		await fetch(`${url}`)
			.then(response => {
				return response.json()
			})
			.then(jsonData => {
				this.searchString.isLoading = false;
				this.searchString.message = "";
				if (jsonData.response.application_response_code.substr(0, 1) === '1') {
					console.log('Properties found: ' + jsonData.response.listings.length);
					this.searchString.result = jsonData.response.listings;
					console.log("success");
				} else {
					this.searchString.result.length = 0;
					this.searchString.message = "Location not recognized; please try again.";
				}
			})
			.catch(error => {
				this.searchString.isLoading = false;
				this.searchString.message = "数据请求失败，请稍后重试";
			})
	}
}
export default new SearchData();